/* Symbol table functions. */

#include "defs.h"
#include "data.h"
#include "decl.h"

static int Globs = 0;   // position of next free global symbol slot

/*
 * Determine if the symbol sym is in the global symbol table.
 * Return its slot position or -1 if not found.
 */
int findglob(char *sym)
{
    for (int i = 0; i < Globs; i++) {
        if (*sym == *Gsym[i].name && strcmp(sym, Gsym[i].name) == 0)
            return i;
    }

    return -1;
}

/*
 * Get the position of a new global slot,
 * or die if we're run out of positions.
 */
static int newglob(void)
{
    int pos;

    if ((pos = Globs++) >= NSYMBOLS) 
        fatal("Too many global symbols");

    return pos;
}

/*
 * Add a global symbol to the symbol table.
 * Return the slot number in the symbol table.
 */
int addglob(char *name, int type, int stype)
{
    int slot_id;

    if ((slot_id = findglob(name)) != -1) 
        return slot_id;

    slot_id = newglob();
    Gsym[slot_id].name = strdup(name);
    Gsym[slot_id].type = type;
    Gsym[slot_id].stype = stype;
    return slot_id;
}
